import { useParams,useNavigate } from "react-router-dom";
import { useState } from "react";
import { useLocalStorage } from "react-use";
import { useEffect } from "react";
import { TextField, Button } from "@mui/material";
import { Fab } from "@mui/material";
import HomeIcon from '@mui/icons-material/Home';
import toast from 'react-hot-toast';

function MemoItem() {
    const { id } = useParams();
    
    const [memos, setMemos] = useLocalStorage('memos');
    const navigate = useNavigate();
    const memo = memos.find(memo => memo.id === parseInt(id));
    const [title, setTitle] = useState(memo.title);
    const [content, setContent] = useState(memo.content);
    useEffect(() => {
        setTitle(memo.title);
        setContent(memo.content);
    }, [memo]);
    function handleUpdate() {
        const newMemo = memos.map(memo => 
            memo.id === parseInt(id) ? 
            { ...memo, title: title, content: content } :
             memo);
        setMemos(newMemo);
        setTitle('');
        setContent('');
        toast.success('更新成功');

        navigate('/');
    }
    return (
        <>
        <form style={{display: 'flex', flexDirection: 'column',
             alignItems: 'center'}}>
            <TextField id="outlined-basic" label="title" 
                variant="outlined" 
                style={{marginBottom: '10px'}}
                value={title}
                onChange={(e) => setTitle(e.target.value)}
                />
            <br/>
            <TextField
                id="outlined-multiline-static"
                label="content"
                multiline
                rows={4}
                style={{marginBottom: '10px'}}
                value={content}
                onChange={(e) => setContent(e.target.value)}
                />
            <br/>
            <Button variant="contained" color="primary"
            onClick={handleUpdate}
            >
                update
            </Button>
            <Fab color="primary" aria-label="add"  
            onClick={() => navigate('/')}
            style={{
                position: 'absolute',
                bottom: 56,
                right: 16,
              }}>
                <HomeIcon />
            </Fab>
        </form>
        </>
        
    )
}

export default MemoItem;